﻿#include "plotarea.h"

PlotArea::PlotArea() : QCustomPlot()
{
    plotLayout()->clear();

    QCPAxisRect *wideAxisRect = new QCPAxisRect(this);
    wideAxisRect->setupFullAxesBox(true);
    wideAxisRect->axis(QCPAxis::atRight, 0)->setTickLabels(true);
    wideAxisRect->removeAxis(wideAxisRect->axis(QCPAxis::atRight));
    wideAxisRect->removeAxis(wideAxisRect->axis(QCPAxis::atTop));
    wideAxisRect->axis(QCPAxis::atLeft)->setRange(-1.5, 1.5);
    plotLayout()->addElement(0, 0, wideAxisRect);

}

PlotArea::~PlotArea()
{

}

double PlotArea::getAxisRange() const
{
    return axisRange;
}

void PlotArea::setAxisRange(double value)
{
    axisRange = value;
    axisRect()->axis(QCPAxis::atBottom)->setRange(0,axisRange);
}

void PlotArea::addPointGraphMap(PointStream *points)
{
    if(pointGraphMap.count()>=MAX_GRAPHNUM)
    {
        return ;
    }
    QCPGraph *graph = addGraph(axisRect(0)->axis(QCPAxis::atBottom), axisRect(0)->axis(QCPAxis::atLeft));
    QPen pen;
    pen.setColor(QColor(Qt::red));
    pen.setWidth(1.6);
    graph->setPen(pen);
    graph->setLineStyle(QCPGraph::lsLine);
    /*
     * Add a new point stream and a graph that is associated
     * to this pointStream to the Plot Area.
     */
    pointGraphMap.insert(points, graph);

}

void PlotArea::update()
{
         for(PointStream *stream : pointGraphMap.keys()) {
                QList<QPointF> data = stream->getRecentPoints(stream->getSamplesPerSeconds() * axisRange);
                QCPDataMap *dataMap = new QCPDataMap();
                quint32 windowNumberLastSample = ((quint32)data.last().x())/((quint32)(axisRange*stream->getSamplesPerSeconds()));
                for(int i=data.size()-1; i>=0; i--) {
                    QPointF point = data[i];
                    quint32 windowNumber = ((quint32)point.x())/((quint32)(axisRange*stream->getSamplesPerSeconds()));
                    if(windowNumber != windowNumberLastSample) {
                        break;
                    }
                    double x = (double)(((quint32)point.x())%((quint32)(axisRange*stream->getSamplesPerSeconds())))/((double)stream->getSamplesPerSeconds());
                    dataMap->insert(x, QCPData(x,point.y()));
                }
                pointGraphMap[stream]->setData(dataMap, false);
            }

            //axisRect()->axis(QCPAxis::atLeft)->rescale(true);

            replot();
 }
